package org.openkoala.security.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.security.facade.SecurityAccessFacade;
import org.openkoala.security.facade.command.LoginCommand;
import org.openkoala.security.facade.dto.UserDTO;
import org.openkoala.security.shiro.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dhcc.DRGsHosp.facade.DepartmentFacade;
import com.dhcc.DRGsHosp.facade.LoginInfoFacade;
import com.dhcc.DRGsHosp.facade.dto.DepartmentDTO;
import com.dhcc.DRGsHosp.facade.dto.LoginInfoDTO;

/**
 * 登陆用户控制器。
 * 
 * @author lucas
 * 
 */
@Controller
@RequestMapping
@SuppressWarnings("unused")
public class LoginController {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
	
	@Inject
	private DepartmentFacade departmentFacade;
	@Inject
	private LoginInfoFacade loginInfoFacade; 
	@Inject
	private SecurityAccessFacade securityAccessFacade; 

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
       if(CurrentUser.getSubject().isAuthenticated()){
            return "redirect:index.dhc";
        }
		return "login";
	}

	/** 如果登陆了 就不用再次到登陆页面，直接就可以进入。
	 * 用户登陆
	 * 
	 * @param request
	 * @param command
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public InvokeResult login(HttpServletRequest request, LoginCommand command) {
		//首先验证License
		//String licenseFile = LoginController.class.getResource("/").getFile()+"/drgsLicense.lic";
		Date currentDate = new Date();
		 //获取当前医院code
		List<Object[]> list = departmentFacade.queryHoptalCode();	
		String hospCode_="";
		if(list.isEmpty()){
        	hospCode_="";
        }else{
        	Object[] hospCode=list.get(0);
            hospCode_= hospCode[0].toString();
        }
//		try {
//			CheckLicense.licMsg = "success";
//			if(!CheckLicense.checkLicenseFile(licenseFile, "", currentDate,hospCode_)){
//				System.out.println(CheckLicense.licMsg);
//				return InvokeResult.success(CheckLicense.licMsg);
//			}
//			if(!"".equals(CheckLicense.licMsg)){
//				System.out.println(CheckLicense.licMsg);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		InvokeResult invokeResult =	 doCaptcha(request);// 处理验证码
		if(!invokeResult.isSuccess()){
			return invokeResult;
		}else{
			UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
					command.getUsername(),
					command.getPassword(),
					command.getRememberMe());
			try {
				SecurityUtils.getSubject().login(usernamePasswordToken);
				
				/**
				 * 添加分段科室信息
				 */
				UserDTO userDto = securityAccessFacade.getUserByUserAccount(CurrentUser.getUserAccount());
				CurrentUser.getPrincipal().setDepYb(userDto.getDepYb());
				
				DepartmentDTO dto = departmentFacade.getCurrentUserDepartment(CurrentUser.getUserAccount());
				if(dto != null){
					CurrentUser.getPrincipal().setDepCode(dto.getDepCode());
					CurrentUser.getPrincipal().setDepName(dto.getDepName());
					LoginInfoDTO loginDto= buildDto(command.getUsername(), dto.getDepName(),"1");
					loginInfoFacade.creatLoginInfo(loginDto);
					
				}else{
					LoginInfoDTO loginDto= buildDto(command.getUsername(), CurrentUser.getName(),"1");
					loginInfoFacade.creatLoginInfo(loginDto);
				}
				return InvokeResult.success("success");
			} catch (UnknownAccountException e) {
				LOGGER.error(e.getMessage(), e);
				return InvokeResult.failure("账号或者密码不存在。");			
			} catch (LockedAccountException e) {
				LOGGER.error(e.getMessage(), e);
				return InvokeResult.failure("该用户已禁用，请联系管理员。");			
			} catch (AuthenticationException e) {
				LOGGER.error(e.getMessage(), e);
				return InvokeResult.failure("账号或者密码不正确。");
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
				return InvokeResult.failure("登录失败。");
			}
		}
	}

	/**
	 * 处理验证码
	 * 
	 * @param request
	 * @return
	 */
	private InvokeResult doCaptcha(HttpServletRequest request) {
		/*String shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
		if (!StringUtils.isBlank(shiroLoginFailure)) {
			return	InvokeResult.failure("验证码错误。");
		}*/
		return InvokeResult.success();
	}
	
	/**
	 * 
	 * @methodname :buildDto
	 * @description : 组装loginLogDto
	 * @param :
	 * @author :pcnicky
	 * @return :
	 * @date :2014年1月21日
	 */
	private LoginInfoDTO buildDto(String userCode, String userName,String loginType) {
		LoginInfoDTO loginInfoDto = new LoginInfoDTO();
		loginInfoDto.setLoginId(UUID.randomUUID().toString());
		loginInfoDto.setLoginUserCode(userCode);
		loginInfoDto.setLoginUserName(userName);
		loginInfoDto.setLoginTime(new Date());
	
		// 获取本机IP
//		ObtainLocalhostIpAddress ipAddress = new ObtainLocalhostIpAddress();
//		loginLog.setLoginIp(ipAddress.getLocalhostIp());
		// 登陆类型
		loginInfoDto.setLoginType(loginType);
	
		return loginInfoDto;
	}
}
